import axios from 'axios'

axios.interceptors.request.use(config => {
  config.headers = { ...config.headers, 'Cache-Control': 'no-cache' }

  const r = Math.random();
  if (config.url.includes("?")) {
    config.url = config.url + "&v=" + r;
  } else {
    config.url = config.url + "?v=" + r;
  }
  return config
})

function queryParams(params) {
  return params ? Object.keys(params)
    .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
    .join('&') : '';
}

export const genUrlFromParams = (url, params) => {
  if (url && params) {
    params = { ...params }
    url += (url.indexOf('?') === -1 ? '?' : '&') + queryParams(params)
  }

  return url
}

export const fetchGet = (url, params, axiosExtendOps = {}) => {
  return fetchGetWithHeaders(url, params, {}, axiosExtendOps);
}

export const fetchGetWithHeaders = (url, params, headers = {}, axiosExtendOps = {}) => {
  url = genUrlFromParams(url, params)
  let ops = {
    withCredentials: true,
    responseType: 'json',
    headers: Object.assign({
      'Accept': 'application/json',
      'Content-Type': 'application/json;charset=utf-8'
    }, headers)
  }
  Object.assign(ops, axiosExtendOps);
  return axios.get(url, ops)
}

export const fetchPost = (url, params, axiosExtendOps = {}) => {
  return fetchPostWithHeaders(url, params, {}, axiosExtendOps)
}

export const fetchPostWithHeaders = (url, params, headers = {}, axiosExtendOps = {}) => {
  let ops = {
    withCredentials: true,
    responseType: 'json',
    headers: Object.assign({
      'Accept': 'application/json',
      'Content-Type': 'application/json;charset=utf-8'
    }, headers)
  };
  Object.assign(ops, axiosExtendOps);
  return axios.post(url, params, ops)
}
